package com.lzx.adx.report.controller.v1.xiaomi;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.WphCovertBaiduEnums;
import com.lzx.adx.report.enums.WphCovertXiaoMiEventTypeEnums;
import com.lzx.adx.report.enums.XhsCovertXmEventTypeEnums;
import com.lzx.adx.report.model.xiaomi.XiaoMiRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.helper.WphHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/xiaomi/xhs")
@Slf4j
public class XiaoMiXhsController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    public static final String apiDesc = "小米-小红书";


    @GetMapping("/report")
    public ResponseEntity report(XiaoMiRequest requestParams, HttpServletRequest request) {
        log.info("接收到xiaomi-elm【{}】的请求参数为{}", apiDesc, JsonUtils.toJsonString(requestParams));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(requestParams);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(requestParams));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });

        //获取配置信息
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(requestParams.getDspId());
        //3.处理参数和URL
        String resultUrl = UrlUtil.handXhsReplace(reportDTO, accountDTO);
        log.info("账户号为{}，完整的小红书请求地址为{}", requestParams.getDspId(), resultUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(resultUrl).execute().body();
        log.info("账户号为{}，上报小红书的接口，响应的结果为{}", requestParams.getDspId(), body);
        JSONObject jsonObject = JSONObject.parseObject(body);
        //响应状态码成功
        if (jsonObject.getInteger("code").equals(0)) {
            return ResponseEntity.ok(new Result());
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }


    /**
     * 小红书
     *
     * @param click_id  请求事件ID
     * @param conv_type 转换类型
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String click_id, String conv_type, String conv_ts) throws Exception {
        log.info("小米接收了小红书的回调信息，请求流水号{},回调类型为{},时间为{}，", click_id, conv_type, conv_ts);
        if (StringUtils.isBlank(click_id) || StringUtils.isBlank(conv_type)) {
            log.info("小米接收了小红书的回调信息参数异常空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        XhsCovertXmEventTypeEnums xhsEnums = XhsCovertXmEventTypeEnums.getQqyCode(conv_type);
        if (null == xhsEnums) {
            log.info("小米接收了小红书的回调信息 流水号是{} 指标是{}，非注册指标拒绝回传", click_id, conv_type);
            return ResponseEntity.ok(new Result());
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", click_id);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        //获取配置的秘钥，获取不到标识没关注此事件
        String singKey = jsonObject.getString(conv_type);
        if (StringUtils.isBlank(singKey)) {
            log.info("账户id{}请求流水号{} 不关注此事件{}", reportDTO.getDspId(), click_id, conv_type);
            return ResponseEntity.ok(new Result());
        }
        reportDTO.setResultType(conv_type);
        reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,conv_type);
        Map<String, String> reqMap = new LinkedHashMap<>();
        reqMap.put("callback", URLEncoderDecoderTool.encodeURL(reportDTO.getCallback()));
        if (StringUtils.isNotBlank(reportDTO.getOaid())) {
            reqMap.put("oaid", reportDTO.getOaid());
        } else if (StringUtils.isNotBlank(reportDTO.getImei())) {
            reqMap.put("imei", reportDTO.getImei());
        }
        reqMap.put("conv_time", reportDTO.getResultTime());
        reqMap.put("convType", xhsEnums.getCode());
        log.info("账户{}请求流水号为{}，获取的小米code为{}，秘钥为{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), xhsEnums.getCode(), singKey);
        String url = URLUtil.buildQuery(reqMap, StandardCharsets.UTF_8);
        String sign = SecureUtil.md5(url + singKey);
        String resultUrl = accountDTO.getSspApiUrl() + "?" + url + "&sign=" + sign;
        log.info("账户{}请求流水号为{}xhs给小米回传的完整地址为{}", reportDTO.getDspId(), click_id, resultUrl);
        String rsult = HttpUtil.get(resultUrl);
        log.info("账户{}请求流水号为{}xhs饿了么回调给小米的结果为{}", reportDTO.getDspId(), click_id, rsult);
        return ResponseEntity.ok(new Result());
    }


}
